import { defineConfig } from "rollup";
import { nodeResolve } from "@rollup/plugin-node-resolve";
import commonjs from "@rollup/plugin-commonjs";
import alias from "@rollup/plugin-alias";
import json from "@rollup/plugin-json";
import esbuild from "rollup-plugin-esbuild";
import image from "@rollup/plugin-image";

import { builtinModules } from "module";
import { resolve } from "path";


import { App_Env_Enum, App_Modules_Enum, App_NODE_ENV_Enum } from "../enum/app.enum";
import { Env } from "../utils/env";

const external = [
  ...builtinModules, 
  "electron",
  "axios",
  "electron-updater",
  "express"
];


export default function rollupConfig(
  type: App_Modules_Enum = App_Modules_Enum.MAIN
) {


  return defineConfig({
    input: resolve(
      "src/" + (
        type === App_Modules_Enum.MAIN
        ? "main/index.ts"
        : "preload/index.ts"
      )
    ),
    output: {
      file: resolve(
        "dist/electron/" + (  
          type === App_Modules_Enum.MAIN
          ? "main/index.js"
          : "preload/index.js"
        )
      ),
      format: "cjs",
      sourcemap: false,
    },
    plugins: [
      nodeResolve({
        preferBuiltins: true,
        browser: false,
        extensions: [".mjs", ".ts", ".js", ".json", ".node"],
      }),
      commonjs({
        sourceMap: false,
      }),
      json(),
      image(),
      esbuild({
        include: /\.[jt]s?$/,
        exclude: /node_modules/,
        sourceMap: false,
        minify: Env.getEnv(App_Env_Enum.NODE_ENV)  === App_NODE_ENV_Enum.PRODUCTION,
        target: "esnext",
        define: {
          __VERSION__: '"x.y.z"',
        },
        loaders: {
          ".json": "json",
          // todo
          ".js": "jsx",
          ".ts": "ts",
        },
      }),
      alias({
        entries: [
          { find: "@config", replacement: resolve("config") },
          { find: "@scripts", replacement: resolve("scripts") },
          { find: "@types", replacement: resolve("types") },
          { find: "@application", replacement: resolve("src/application") },
          { find: "@main", replacement: resolve("src/main") },
          { find: "@preload", replacement: resolve("src/preload") },
          { find: "@utils", replacement: resolve("utils") },
          { find: "@enum", replacement: resolve("enum") },
          { find: "@resources", replacement: resolve("resources") },
        ],
      }),
    ],
    external,
  });
}
